<template>
    <div>
        <!-- 搜索栏 -->
        <div style="margin: 5px;text-align: center;">
            <el-input v-model="name" @click.enter.native="loadPost()" placeholder="请输入用户账号"
                style="width: 200px;margin-left: 5px;;" prefix-icon="el-icon-search"></el-input>

            <el-input v-model="username" @click.enter.native="loadPost()" placeholder="请输入用户姓名"
                style="width: 200px;margin-left: 5px;;" prefix-icon="el-icon-search"></el-input>

            <el-input v-model="telephone" @click.enter.native="loadPost()" placeholder="请输入用户手机号"
                style="width: 200px;margin-left: 5px;;" prefix-icon="el-icon-search"></el-input>

            <el-input v-model="email" @click.enter.native="loadPost()" placeholder="请输入用户邮箱"
                style="width: 200px;margin-left: 5px;;" prefix-icon="el-icon-search"></el-input>


        </div>
        <div style="margin: 5px;text-align: center;">
            <el-select v-model="sex" @change="loadPost()" placeholder="请选择用户性别" style="width: 200px;margin-left: 5px;;">
                <el-option v-for="item in sexData" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="role" @change="loadPost()" placeholder="请选择用户角色"
                style="width: 200px;margin-left: 5px;;">
                <el-option v-for="item in roleData" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="status" @change="loadPost()" placeholder="请选择用户状态"
                style="width: 200px;margin-left: 5px;;">
                <el-option v-for="item in statusData" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>

            <el-button type="success" icon="el-icon-search" @click="loadPost()" circle
                style="margin-left: 5px;"></el-button>
            <el-button type="success" icon="el-icon-refresh" @click="resetParam" circle
                style="margin-left: 5px;"></el-button>
            <el-button type="primary" icon="el-icon-plus" @click="add" circle style="margin-left: 5px;"
                v-if="hasAuth('user-save')"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delHandle(null)" circle style="margin-left: 5px;"
                v-if="hasAuth('user-delete')" :disabled="delBtnStatus"></el-button>

        </div>
        <el-table :data="tableData" ref="multipleTable" tooltip-effect="dark" border style="width: 100%" stripe
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="用户头像" width="100" prop="avatar" align="center">
                <template slot-scope="scope">
                    <el-avatar :src="scope.row.avatar" :size="50"></el-avatar>
                </template>
            </el-table-column>

            <el-table-column label="用户账号" width="100" prop="name" align="center">
            </el-table-column>
            <el-table-column label="用户姓名" width="100" prop="username" align="center">
            </el-table-column>
            <el-table-column label="用户密码" width="100" prop="password" v-if="user.role == 1" align="center">
            </el-table-column>
            <el-table-column label="用户性别" width="100" prop="sex" align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.sex == 0" type="danger">女</el-tag>
                    <el-tag v-else type="success">男</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="用户手机" width="100" prop="telephone" align="center">
            </el-table-column>
            <el-table-column label="用户邮箱" width="100" prop="email" align="center">
            </el-table-column>
            <el-table-column label="用户角色" width="100" prop="role" align="center" :formatter="formatRole">

            </el-table-column>
            <el-table-column label="用户年龄" width="100" prop="age" align="center">
            </el-table-column>
            <el-table-column label="用户状态" width="200" prop="status" align="center">
                <template slot-scope="scope">
                    <el-switch :value="scope.row.status == 1" active-text="正常" active-color="#13ce66"
                        :disabled="!hasAuth('user-modStatus')" inactive-color="#ff4949" inactive-text="注销"
                        @change="modStatus(scope.row.id)"></el-switch>
                </template>
            </el-table-column>

            <el-table-column label="注册时间" width="180" prop="createTime" align="center"
                :formatter="formatDate"></el-table-column>

            <el-table-column label="修改时间" width="180" prop="updateTime" align="center"
                :formatter="formatDate"></el-table-column>
            <el-table-column label="操作" width="300" align="center" fixed="right">
                <template v-slot="scope">
                    <div v-if="scope.row.role != 1">
                        <el-button type="success" icon="el-icon-edit" @click="mod(scope.row)" circle
                            v-if="hasAuth('user-update')" style="margin-left: 5px;"></el-button>
                        <el-button type="danger" icon="el-icon-delete" @click="delHandle(scope.row.id)" circle
                            style="margin-left: 5px;" v-if="hasAuth('user-delete')"></el-button>

                        <el-button type="success" icon="el-icon-refresh" @click="repass(scope.row)" circle
                            v-if="hasAuth('user-repass')" style="margin-left: 5px;"></el-button>
                        <el-button type="primary" icon="el-icon-rank" @click="roleHandle(scope.row.id)" circle
                            style="margin-left: 5px;" v-if="hasAuth('user-role')"></el-button>

                    </div>

                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
            :page-size="pageSize" :page-sizes="[5, 20, 50, 100, 1000]" background
            layout="total,sizes,prev, pager, next,jumper" :total="total">
        </el-pagination>
        <el-dialog title="用户表单" :visible.sync="dialogVisible" width="80%" center>
            <el-form :model="form" ref="form" label-width="150px" :rules="rules"
                style="width: 800px;margin: 10px auto;;" enctype="multipart/form-data">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户账号" prop="name">
                            <el-input v-model="form.name" placeholder="请输入用户账号" style="width: 200px;"></el-input>
                        </el-form-item>
                        <el-form-item label="用户姓名" prop="username">
                            <el-input v-model="form.username" placeholder="请输入用户姓名" style="width: 200px;"></el-input>
                        </el-form-item>
                        <!-- 手机号码 -->
                        <el-form-item label="手机号码" prop="telephone">
                            <el-input v-model="form.telephone" placeholder="请输入手机号码" style="width: 200px;"></el-input>
                        </el-form-item>
                        <el-form-item label="用户邮箱" prop="email">
                            <el-input v-model="form.email" placeholder="请输入用户邮箱" style="width: 200px;"></el-input>
                        </el-form-item>
                        <el-form-item label="用户密码" prop="password">
                            <el-input v-model="form.password" type="password" placeholder="请输入用户密码"
                                style="width: 200px;"></el-input>
                        </el-form-item>

                        <!-- 用户年龄 -->
                        <el-form-item label="用户年龄" prop="age">
                            <el-input-number v-model="form.age" type="number" :min="18" :max="50" placeholder="请输入用户年龄"
                                style="width: 200px;"></el-input-number>
                        </el-form-item>
                        <!-- 用户性别 -->
                        <el-form-item label="用户性别" prop="sex">
                            <el-select v-model="form.sex" placeholder="请选择性别" style="width: 200px;">
                                <el-option v-for="item in sexData" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 用户头像 -->
                        <el-form-item label="用户头像" prop="avatar">
                            <el-upload action="#" list-type="picture-card" :auto-upload="false"
                                :on-change="submitUpload" :limit="1" :file-list="fileList">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                        </el-form-item>
                        <!-- 用户角色 -->
                        <el-form-item label="用户角色" prop="role" v-if="form.update == 0">
                            <el-radio-group v-model="form.role" placeholder="请选择角色" style="width: 200px;">
                                <div v-for="item in roleData" :key="item.id">
                                    <el-radio v-if="item.register == 1" :label="item.id" style="margin-top: 10px;">{{
                                        item.name }}
                                    </el-radio>
                                </div>

                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                </el-row>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="角色分配" :visible.sync="roleDialogVisible" width="600px" center>

            <el-radio-group v-model="form.role" placeholder="请选择角色" style="width: 200px;">
                <div v-for="item in roleData" :key="item.id">
                    <el-radio v-if="item.register == 1" :label="item.id" style="margin-top: 10px;">{{
                        item.name }}
                    </el-radio>
                </div>
            </el-radio-group>

            <div slot="footer" class="dialog-footer">
                <el-button @click="roleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="doMod">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
    // eslint-disable-next-line vue/multi-word-component-names
    name: 'User',
    data() {
        return {
            user: JSON.parse(localStorage.getItem('CurUser')),
            tableData: [],

            total: 0,
            pageSize: 5,
            pageNum: 1,
            delBtnStatus: true,
            multipleSelection: [],
            name: '',
            username: '',
            telephone: '',
            email: '',
            sex: '',
            status: 1 + '',

            role: '',
            sexData: [
                { name: '男', id: 1 },
                { name: '女', id: 0 }
            ],
            statusData: [
                { name: '正常', id: '1' },
                { name: '注销', id: '0' },
            ],
            roleData: [],
            dialogVisible: false,
            roleDialogVisible: false,
            form: {
                name: '',
                username: '',
                password: '',
                rpassword: '',
                email: '',
                telephone: '',
                sex: 1,
                age: '',
                role: '',
                avatar: '',
                update: 0
            },
            rules: {
                name: [
                    { required: true, message: '请输入用户账号', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到8 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在 6 到 16个字符', trigger: 'blur' }
                ],

                sex: [
                    { required: true, message: '请选择性别', trigger: 'change' }
                ],
                age: [
                    { required: true, message: '请选择年龄', trigger: 'change' }
                ],
                avatar: [
                    { required: true, message: '请上传头像', trigger: 'change' }
                ],
                telephone: [
                    { required: true, message: '请填写手机号', trigger: 'blur' },
                    { min: 11, max: 11, message: '请填写11位手机号', trigger: 'blur' },
                    { pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(18[0-9])|166|198|199|(147))\d{8}$/, message: "手机号码不正确" }
                ],
                email: [
                    { required: true, message: '请填写邮箱', trigger: 'blur' },
                    { type: 'email', message: '请填写正确的邮箱', trigger: 'blur' }
                ],
                role: [
                    { required: true, message: '请选择角色', trigger: 'change' }
                ],



            },
            fileList: [],

        }
    },
    methods: {
        resetParam() {
            this.name = ''
            this.sex = ''
            this.status = ''
            this.role = ''
            this.username = ''
            this.telephone = ''
            this.email = ''
        },
        loadPost() {
            this.$axios.post('/user/listPage',
                {
                    pageSize: this.pageSize,
                    pageNum: this.pageNum,
                    param: {
                        name: this.name + '',
                        sex: this.sex + '',
                        role: this.role + '',
                        username: this.username + '',
                        telephone: this.telephone + '',
                        email: this.email + '',
                        status: this.status + ''
                    }
                }).then(res => {
                   
                    if (res.code == 200) {
                        this.tableData = res.data
                        // console.log(res.data)
                        if (res.data.length == 0 && this.pageNum != 1) {
                            this.pageNum = 1;
                            this.loadPost()
                        }
                        this.total = res.total
                    }
                })
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.pageNum = 1
            this.loadPost()
        },
        handleCurrentChange(val) {
            this.pageNum = val
            this.loadPost()
        },
        formatDate(row, column) {
            let data = row[column.property]
            if (data == null)
                return null
            let date = new Date(data)
            return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
        },
        loadRole() {
            this.$axios.post('/role/listPage', {
                pageSize: 1000,
                pageNum: 1,
                param: {
                }
            }).then(res => {
               
                if (res.code == 200) {
                    this.roleData = res.data
                    console.log(this.roleData)
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        formatRole(row) {
            let temp = this.roleData.find(item => item.id == row.role)
            return temp && temp.name;
        },
        add() {
            this.resetForm()
            this.dialogVisible = true

        },
        mod(row) {
            this.$axios.get('/user/info/' + row.id).then(res => {
                this.form = res.data.data
                if (this.form.avatar != null) {
                    this.fileList = []
                    this.fileList.push({ url: this.form.avatar })
                }
                this.form.update = 1
                this.dialogVisible = true
            })

        },
        save() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    if (this.form.id) {
                        this.doMod()
                    } else {
                        this.doSave()
                    }
                } else {
                    this.$message({
                        message: '校验失败',
                        type: 'warning'
                    })
                }
            })
        },
        doMod() {
            this.$axios.post('/user/update', this.form).then(res => {
               
                if (res.code == 200) {
                    this.$message.success({
                        message: '修改成功',
                        type: 'success',
                        onClose: () => {
                            this.loadPost()
                            this.dialogVisible = false
                            this.roleDialogVisible = false
                            this.resetForm()
                        }
                    })
                } else {
                    this.$message({
                        message: res.msg,
                        type: 'error'
                    })
                }
            })

        },
        doSave() {
            this.$axios.post('/user/save', this.form).then(res => {
               
                if (res.code == 200) {
                    this.$message.success({
                        message: '新增成功',
                        type: 'success',
                        onClose: () => {
                            this.loadPost()
                            this.dialogVisible = false
                            this.resetForm()
                        }
                    })
                } else {
                    this.$message({
                        message: '新增失败',
                        type: 'error'
                    })
                }
            })
        },
        resetForm() {
            this.form = {
                name: '',
                username: '',
                password: '',
                rpassword: '',
                email: '',
                telephone: '',
                sex: 1,
                age: '',
                role: '',
                avatar: '',
                update: 0
            }
            this.fileList = []
        },
        submitUpload(file) {
            let formData = new FormData();
            formData.append("file", file.raw);
            formData.append("name", file.name);
            this.$axios.post('/file/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then(res => {
               
                console.log(res)
                if (res.code == 200) {
                    this.form.avatar = res.data.url
                    this.$message({
                        message: "上传成功",
                        type: "success"
                    })
                } else {
                    this.$message({
                        message: '上传失败',
                        type: 'error'
                    })
                }
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
            this.delBtnStatus = val.length == 0
        },
        delHandle(id) {
            var ids = []
            if (id) {
                //单删
                ids.push(id)
            } else {
                //批量删
                this.multipleSelection.forEach(item => {
                    ids.push(item.id)
                })
            }
            this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post('/user/deleteBatch', ids, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(res => {
                   
                    if (res.code == 200) {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        this.loadPost()
                    } else {
                        this.$message({
                            message: '删除失败',
                            type: 'error'
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    message: '已取消',
                    type: 'info'
                })
            })
        },
        roleHandle(id) {
            this.$axios.get('/user/info/' + id).then(res => {
                this.form = res.data
                this.roleDialogVisible = true
            })

        },
        modStatus(id) {
            this.$axios.post('/user/modStatus/' + id).then(res => {
               
                if (res.code == 200) {
                    this.$message.success({
                        message: '操作成功',
                        type: 'success',
                        onClose: () => {
                            this.loadPost()
                        }
                    }
                    )
                } else {
                    this.$message({
                        message: '操作失败',
                        type: 'error'
                    })


                }
            })
        },
        repass(row) {
            this.$confirm('确定要重置用户【' + row.username + '】的密码吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                this.$axios.post('/user/repass/' + row.id).then(res => {
                   
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: res.msg
                        })
                        this.loadPost()
                    } else {
                        this.$message({
                            type: 'error',
                            message: res.msg
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    message: '已取消',
                    type: 'info'
                })
            })
        }
    },
    computed: {
        ...mapGetters([
            'hasAuth'
        ])
    }, mounted() {
        this.loadRole()
        this.loadPost()
    },
}
</script>
<style scoped>
.el-pagination {
    text-align: center;
    margin-top: 22px;
}
</style>